<?php

namespace app\health\controller;

use app\health\model\HealthArticle;
use app\health\model\HealthArticleCategory;

class Article extends ApiBase
{
    protected $noNeedLogin = ['category', 'lists', 'detail'];

    /**
     * 获取文章分类
     * @Author 张旭鹏
     * @DateTime 2023-06-14
     */
    public function category()
    {
        $category = HealthArticleCategory::where(['status' => 'normal'])->field('id,name')->order('sort', 'desc')->select();
        $data = [
            ['id' => 'hot', 'name' => '热门'],
            ['id' => 'new', 'name' => '最新'],
        ];
        foreach ($category as $item) {
            $data[] = ['id' => (string)$item['id'], 'name' => $item['name']];
        }
        $this->success('', $data);
    }

    /**
     * 文章列表
     * @Author 张旭鹏
     * @DateTime 2023-06-14
     */
    public function lists()
    {
        $limit    = $this->request->param('limit/d', 10);
        $where = [
            'status' => ['=', 'normal']
        ];
        $field = ['id', 'title', 'image', 'actual_views', 'virtual_views', 'create_time', 'is_top'];
        $orderBy = ['is_top' => 'desc', 'sort' => 'desc'];
        $paginate = HealthArticle::where($where)
            ->field($field)
            ->order($orderBy)
            ->paginate($limit)
            ->each(function ($item) {
                $image = explode(',', $item->image);
                foreach ($image as &$value) {
                    $value = cdnurl($value, true);
                }
                $item->image = $image;
                $item->create_time = date('Y-m-d H:i:s', $item->create_time);
                $item->hidden(['virtual_views', 'actual_views']);
            });
        $this->success('', $paginate);
    }

    /**
     * 文章详情
     * @Author 张旭鹏
     * @DateTime 2023-06-14
     */
    public function detail()
    {
        $articleId = $this->request->param('article_id');
        if (empty($articleId)) {
            $this->error('请选择文章');
        }
        $article = HealthArticle::getById($articleId);
        if (!$article) {
            $this->error('文章不存在');
        }
        if ($article['status'] !== 'normal') {
            $this->error('文章已下架');
        }
        $totalViews = $article->total_views;
        $article->actual_views += 1;
        $article->save();
        $this->success('', [
            'title' => $article->title,
            'image' => cdnurl($article->image, true),
            'content' => $article->content,
            'author' => $article->author,
            'total_views' => $totalViews,
            'create_time' => date('Y-m-d H:i:s', $article->create_time),
        ]);
    }
}
